﻿//=======================================================
// 作者：LR
// 描述：
// 创建时间：2019-12-26 09:18:10
//=======================================================
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using HarmonyLib;
using System.Reflection;

public class GameObjectOverrideInspector : Editor
{
    public static List<System.Action<GameObject>> GUIHander = new List<System.Action<GameObject>>();
}

public class ILGameObjectOverrideInspector
{
    const string targetStr = "target";
    const string methodStr = "OnHeaderGUI";
    const string typeStr   = "GameObjectInspector";
    static Harmony hook;

    [InitializeOnLoadMethod]
    static void InitHarmony()
    {
        if (hook != null) hook.UnpatchAll();

        hook = new Harmony(typeStr);
        hook.PatchAll();
    }

    [HarmonyPatch(typeStr, methodStr)]
    class ILGameObjectInspector
    {
        public class GameObjectHander
        {
            public object main;
            public object target;

            public GameObjectHander(object main)
            {
                this.main = main;
                var field = main.GetType().GetProperty(targetStr, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                target    = field.GetValue(main) as GameObject;
            }
        }

        static GameObjectHander hander;


        static void Postfix(object __instance)
        {
            if (hander == null || hander.main != __instance)
            {
                hander = new GameObjectHander(__instance);
            }

            var c = GUI.color;
            GUI.color = Color.yellow;
            foreach (var item in GameObjectOverrideInspector.GUIHander)
            {
                item?.Invoke(hander.target as GameObject);
            }
            GUI.color = c;
        }
    }
}

